package com.jibei.mendo.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.hardware.usb.UsbManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.jibei.mendo.ActivityManager;
import com.jibei.mendo.R;
import com.jibei.mendo.event.Event;
import com.jibei.mendo.utils.ClientUtil;
import com.jibei.mendo.utils.Constant;
import com.jibei.mendo.utils.EventBusUtil;
import com.jibei.mendo.utils.ExcelUtil;
import com.jibei.mendo.utils.NetWorkUtil;
import com.jibei.mendo.utils.ServerUtil;
import com.jibei.mendo.utils.ThreadPoolUtils;
import com.jibei.mendo.utils.VibratorUtil;
import com.jibei.mendo.utils.languageUtil;
import com.physicaloid.lib.Boards;
import com.physicaloid.lib.Physicaloid;
import com.physicaloid.lib.programmer.avr.UploadErrors;
import com.physicaloid.lib.usb.driver.uart.ReadLisener;
import com.physicaloid.lib.usb.driver.uart.UartConfig;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Locale;


/**
 * Created by lhl on 2019/8/17.
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    //    SharedPreferences sharedpreferences;
    public static final String REGEX_NEGATIVE_INTEGER = "^[0-9]*$";
    public int globle_role_var, globle_current_var, globle_index;
    //    private WifiManager.MulticastLock lock;
    Locale myLocale = new Locale("ru", "RU");
    long currentTime, lastTime;
    boolean isreceivedFServer = false;
    boolean isThreadRun = false;
    boolean lastIsThreadRun = false;
    private ImageView iv_back;
    private Button btn_udp_send;
    private Button btn_lan_ch, btn_lan_ru, btn_lan_en;
    private Button btn_update_main_dev;
    private Button btn_update_sub_dev;
    private Button btn_avatar_state;
    private Button btn_apply_seeting;
    private TextView communacation_delay_context;
    private TextView Device_id_Context;
    private TextView smpte_audio_item;
    private TextView smpte_audio_context;
    private static TextView Tcp_ip_context;
    private TextView tv_usb, tv_audio, tv_network, tv_btn;
    private Physicaloid mPhysicaloid;
    //****************************************************************
    // TODO : get intent when a USB device detached
    BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                closeDevice();
            }
        }
    };
    private long lastElapseTimeInt;
    private Physicaloid.UploadCallBack mUploadCallback = new Physicaloid.UploadCallBack() {
        @Override
        public void onPreUpload() {
            //            tvAppend(tvRead, "Upload : Start\n");
        }

        @Override
        public void onUploading(int value) {
            //            tvAppend(tvRead, "Upload : " + value + " %\n");
        }

        @Override
        public void onPostUpload(boolean success) {
            if (success) {
                //                tvAppend(tvRead, "Upload : Successful\n");
            } else {
                //                tvAppend(tvRead, "Upload fail\n");
            }
        }

        @Override
        public void onCancel() {
            //            tvAppend(tvRead, "Cancel uploading\n");
        }

        @Override
        public void onError(UploadErrors err) {
            //            tvAppend(tvRead, "Error  : " + err.toString() + "\n");
        }
    };
    private   long lastElapseTimeLong;

    public static  void sendMeg2Server(String message, InetAddress target_host, int target_port) {
//        message = (message == null ? "亲，你的消息呢？" : message);
        Log.d(Constant.TAG, "UDP发送数据:" + message);
        DatagramSocket s = null;// = null;
        try {
            s = new DatagramSocket();
            s.setBroadcast(true);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        int msg_length = message.length();
        byte[] messageByte = message.getBytes();
        DatagramPacket p = new DatagramPacket(messageByte, msg_length, target_host, target_port);
        try {
            assert s != null;
            s.send(p);
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        initView();
        Tcp_ip_context.setEnabled(false);
        Device_id_Context.setEnabled(false);
        restore_data();
    }

    public void restore_data() {

        //获得IP地址的存储
        Tcp_ip_context.setText(SPUtils.getInstance().getString(Constant.REMOTIP, "192.168.1.100"));

        //获得本地ID的存储
        Device_id_Context.setText(SPUtils.getInstance().getString(Constant.LOCALID, 10 + ""));
        //推送本地ID
        EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ID, Device_id_Context.getText().toString()));

        int re = SPUtils.getInstance().getInt(Constant.CURRENTITEM, 4);
        globle_current_var = re;
        //Log.d("ly", "re的存储数据为:" + re);
        if (re >= 1 && re <= 4) {
            init_store_ui(re);
        } else
            init_store_ui(4);

        //获取主机状态下主从角色的存储
        int role = SPUtils.getInstance().getInt(Constant.MASTERSLAVER, 1);
        //Log.d("ly", "role的存储数据为:" + role);
        switch (role) {
            case 1:
                checkRole("1");
                Tcp_ip_context.setEnabled(false);
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ROLE, "Master"));
                break;
            case 2:
                checkRole("2");
                Tcp_ip_context.setEnabled(true);
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ROLE, "Slaver"));
                break;
            default:
                btn_avatar_state.setText(getResources().getString(R.string.fail_detect_role));
                btn_avatar_state.setBackgroundColor(Color.rgb(80, 200, 80));
                break;
        }
    }

    void init_store_ui(int pra1) {
        switch (pra1) {
            case 1:
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.yellow));

                break;
            case 2:
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));

                break;
            case 3:
                tv_usb.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));

                break;
            case 4:
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));

                break;
        }
    }

    private void initView() {
        iv_back = findViewById(R.id.iv_back);
        btn_lan_ch = findViewById(R.id.buttonChinese);
        btn_lan_en = findViewById(R.id.buttonEnglish);
        btn_lan_ru = findViewById(R.id.buttonRussia);
        iv_back.setOnClickListener(this);
        btn_apply_seeting = findViewById(R.id.apply_item);
        communacation_delay_context = findViewById(R.id.Communacation_delay_item);
        btn_udp_send = findViewById(R.id.test001);
        btn_update_main_dev = findViewById(R.id.btn_update_main_dev);
        btn_update_sub_dev = findViewById(R.id.btn_update_sub_dev);
        btn_avatar_state = findViewById(R.id.bt_btn_dev_master);
        Device_id_Context = findViewById(R.id.device_id_context);
        tv_btn = findViewById(R.id.tv_btn);
        tv_audio = findViewById(R.id.tv_audio);
        tv_usb = findViewById(R.id.tv_usb);
        tv_network = findViewById(R.id.tv_network);
        smpte_audio_item = findViewById(R.id.smpte_test_item);
        smpte_audio_context = findViewById(R.id.smpte_context);
        Tcp_ip_context = findViewById(R.id.tcp_ip_context);
        tv_btn.setOnClickListener(this);
        btn_udp_send.setOnClickListener(this);
        btn_apply_seeting.setOnClickListener(this);
        tv_audio.setOnClickListener(this);
        tv_usb.setOnClickListener(this);
        tv_network.setOnClickListener(this);
        btn_update_main_dev.setOnClickListener(this);
        btn_update_sub_dev.setOnClickListener(this);
        btn_avatar_state.setOnClickListener(this);
        mPhysicaloid = new Physicaloid(this);
        btn_lan_ru.setOnClickListener(this);
        btn_lan_en.setOnClickListener(this);
        btn_lan_ch.setOnClickListener(this);
        // 烧录从机用
        UartConfig uartConfig = new UartConfig(115200, UartConfig.DATA_BITS8, UartConfig.STOP_BITS1, UartConfig.PARITY_NONE, false, false);
        mPhysicaloid.setConfig(uartConfig);

        //****************************************************************
        // TODO : register intent filtered actions for device being attached or detached
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, filter);
        //****************************************************************
    }

    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.getInstance().put(Constant.LOCALID, Device_id_Context.getText().toString());
        //****************************************************************
        // TODO : unregister the intent filtered actions
        unregisterReceiver(mUsbReceiver);
        //****************************************************************
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public boolean onActivityReceiveEvents(Event event) {
        boolean isCaptured = false;//子Activity是否捕获事件
        if (super.onActivityReceiveEvents(event)) {
            return isCaptured;
        }
        isCaptured = true;
        switch (event.getTag()) {
            case Constant.Events.UPDATEUI_D:
                String re_t = (String) event.data;
                communacation_delay_context.setText(re_t);
                break;
            case Constant.Events.TIME_CODE:
                String res = (String) event.data;
                smpte_audio_context.setText(res);
                break;
            case Constant.Events.GLOBLE_ROLE:
                String role = (String) event.data;
                if (role.contains("Master"))
                    globle_role_var = 1;
                else
                    globle_role_var = 2;
                break;
            case Constant.Events.DIAN_HUO:
                SPUtils.getInstance().put(Constant.LOCALID, Device_id_Context.getText().toString());
                Log.d("lhl", "setting activity try to save data");
                restore_data();
                Log.d("lhl", "setting activity try to restore data to Main Activity");
                //break;
            case Constant.Events.JIAN_CE:
            case Constant.Events.KONG_DANG:
                restore_data();
            case Constant.Events.READY_PRESS:
            case Constant.Events.DIAN_HUO_PRESS:
                finish();
                break;
            case Constant.Events.ROLE_FROM_EXCEL:
                String role_temp = (String) event.data;
                checkRole(role_temp);
                break;
            case Constant.Events.ID_FROM_EXCEL:
                String id_temp = (String) event.data;
                Device_id_Context.setText(id_temp);
                SPUtils.getInstance().put(Constant.LOCALID, id_temp);
                break;
            default:
                isCaptured = false;
                break;
        }
        return isCaptured;
    }

    public void checkRole(String role) {
        if (role.equals("1")) {
            btn_avatar_state.setText(getResources().getString(R.string.current_master));
            btn_avatar_state.setBackgroundColor(Color.rgb(80, 200, 80));
            globle_role_var = 1;
            if (globle_current_var == 4) {
                try {
                    Tcp_ip_context.setEnabled(false);
                    Tcp_ip_context.setText(NetWorkUtil.getIPAddress(this));
                    Constant.SERVER_IP = NetWorkUtil.getIPAddress(this);
                    ;//Server 的 IP 是从系统获得
                } catch (Exception e) {
                    Tcp_ip_context.setHint(getResources().getString(R.string.no_find_network_check_connection));
                    e.printStackTrace();
                }
            } else
                Tcp_ip_context.setHint(getResources().getString(R.string.work_only_network_mode));

        }
        if (role.equals("2")) {
            globle_role_var = 2;
            btn_avatar_state.setText(getResources().getString(R.string.current_slaver));
            btn_avatar_state.setBackgroundColor(Color.rgb(80, 80, 200));
            if (globle_current_var == 4) {
                Tcp_ip_context.setEnabled(true);
                Tcp_ip_context.setHint(getResources().getString(R.string.input_server_ip_address));
            } else {

                Tcp_ip_context.setEnabled(false);
                Tcp_ip_context.setHint(getResources().getString(R.string.work_only_network_mode));
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        boolean need = false;
        VibratorUtil.getInstance().executeVibrator(SettingActivity.this, 100);
        switch (v.getId()) {
            case R.id.buttonChinese:
                need = languageUtil.updateLocale(this, languageUtil.LOCALE_CHINESE);
                if (need) {
                    ActivityManager.getInstance().recreateAllOtherActivity(this);
                    Toast.makeText(this, "change to chinese", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "no need", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonEnglish:
                need = languageUtil.updateLocale(this, languageUtil.LOCALE_ENGLISH);
                if (need) {
                    ActivityManager.getInstance().recreateAllOtherActivity(this);
                    Toast.makeText(this, "change to english", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "no need", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonRussia:
                need = languageUtil.updateLocale(this, languageUtil.LOCALE_RUSSIAN);
                if (need) {
                    ActivityManager.getInstance().recreateAllOtherActivity(this);
                    Toast.makeText(this, "change to russian", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "no need", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.test001:
//                if (globle_current_var == 4) {
//                    globle_index++;
//                    if (globle_role_var == 1) {
//                        if (MainActivity.isServer2ClientSuccess) {
//                            ServerUtil.getInstance().sendServerMessage(Device_id_Context.getText().toString() + "," + 100);
//                            ToastUtils.showShort(Device_id_Context.getText().toString() + "," + 100);
//
//                            Log.d("ly", "Master send already!");
//                        } else
//                            ToastUtils.showShort(getResources().getString(R.string.please_check_connection));
//                    }
//                    if (globle_role_var == 2) {
//                        if (MainActivity.isClient2ServerSuccess) {
//                            ClientUtil.getInstance().sendClientMessage(Tcp_ip_context.getText().toString() + "," + Device_id_Context.getText().toString() + "," + 100);
//                            ToastUtils.showShort(Tcp_ip_context.getText().toString() + "," + Device_id_Context.getText().toString() + "," + 100);
//                            Log.d("ly", "slaver send already!");
//                        } else
//                            ToastUtils.showShort(getResources().getString(R.string.please_check_connection));
//                    }
//                } else
//                    ToastUtils.showShort(getResources().getString(R.string.work_only_network_mode));
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_update_main_dev:
                //openDevice();
                break;
            case R.id.btn_update_sub_dev:
                openDevice();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    String firmwarePath = ExcelUtil.getInstance().getFirmwarePath();
                    InputStream stream = new FileInputStream(firmwarePath);
                    mPhysicaloid.upload(Boards.ARDUINO_UNO, stream, mUploadCallback);
                } catch (RuntimeException e) {
                    Log.e("lhl", e.toString());
                } catch (IOException e) {
                    Log.e("lhl", e.toString());
                }
                //onClickUpload();
                break;
            case R.id.apply_item://点击应用配置按键：
            {
                String ID = Device_id_Context.getText().toString();//获取ID
                SPUtils.getInstance().put(Constant.LOCALID, ID);//存储ID
                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ID, ID));//推送ID
                SPUtils.getInstance().put(Constant.CURRENTITEM, globle_current_var);
                isThreadRun = true;
                switch (globle_current_var) {
                    case 1:
                        ToastUtils.setBgColor(Color.blue(123));
                        ToastUtils.showShort(getResources().getString(R.string.fire_source_btn_item));
                        break;
                    case 2:
                        ToastUtils.setBgColor(Color.blue(123));
                        ToastUtils.showShort(getResources().getString(R.string.fire_source_audio_item));
                        break;
                    case 3:
                        ToastUtils.setBgColor(Color.blue(123));
                        ToastUtils.showShort(getResources().getString(R.string.fire_source_usb_item));
                        break;
                    case 4: {
                        SPUtils.getInstance().put(Constant.MASTERSLAVER, globle_role_var);//存储角色
                        if (globle_role_var == 1)//推送角色到MainActivity
                        {
                            EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ROLE, "Master"));
                            Tcp_ip_context.setText(NetWorkUtil.getIPAddress(this));
                        }//获取本地IP
                        else
                            EventBusUtil.getInstance().postEvent(new Event(Constant.Events.GLOBLE_ROLE, "Slaver"));

                        boolean isip = RegexUtils.isIP(Tcp_ip_context.getText().toString());
                        if (isip) {//IP 格式正确
                            ServerUtil.getInstance().disconnectServer();//关闭Server
                            ClientUtil.getInstance().disconnectClient();//关闭Client
                            SPUtils.getInstance().put(Constant.REMOTIP, Tcp_ip_context.getText().toString());//存儲當前的ip地址
                        } else {//IP 格式异常
                            ToastUtils.setBgColor(Color.green(255));
                            ToastUtils.showShort(getResources().getString(R.string.ip_error_apply_error));
                            break;
                        }
                        switch (globle_role_var) {
                            case 1://Server port
                            {
                                ThreadPoolUtils.execute(() -> {
                                    //获取锁，使能广播数据接收
                                    //this.lock.acquire();
                                    // 接收的字节大小，客户端发送的数据不能超过这个大小
                                    byte[] message = new byte[100];
                                    try {
                                        // 建立Socket连接
                                        DatagramSocket datagramSocket = new DatagramSocket(Constant.SERVER_PORT);
                                        DatagramPacket datagramPacket = new DatagramPacket(message, message.length);
                                        Log.d(Constant.TAG,"成功建立Socket");
                                        while (isThreadRun) {

                                            // 准备接收数据
                                            Log.d("smartLife", "UDP Client准备接受");
                                            // this.lock.acquire();
                                            try {
                                                datagramSocket.receive(datagramPacket);

                                                String strMsg = new String(datagramPacket.getData()).trim();
                                                //比较是否是服务器的反馈
                                                String ser_addr;
                                                if (strMsg.equalsIgnoreCase(Constant.I_AM_CLIENT)) {
                                                    Log.d(Constant.TAG, "found client");
                                                    ser_addr = datagramPacket.getAddress().getHostAddress();
                                                    if (ser_addr == null) {
                                                        Log.d(Constant.TAG, "are you kidding me ?");
                                                    }
                                                    Log.d(Constant.TAG, ser_addr);
                                                    //sendMeg2Server("FEEDBACK",datagramPacket.getAddress(),Constant.SERVER_PORT);
                                                }
                                                //Log.d(Constant.TAG, datagramPacket.getAddress().getHostAddress() + ":" + strMsg);
                                                if (strMsg.contains("parse")) {
                                                    String[] parse_temp = strMsg.split(",");
                                                    int meg = Integer.parseInt(parse_temp[1]);
                                                    switch (meg) {//收到客户端的消息 解析收到的时间和ID信息
                                                        case 1: {
                                                            String elapseTime = (parse_temp[3]);
                                                            long elapseTime_int = Long.parseLong(elapseTime);
                                                            String ID_temp = (parse_temp[2]);
                                                            long deltaTime = elapseTime_int-1000-lastElapseTimeInt;
                                                            EventBusUtil.getInstance().postEvent(new Event(Constant.Events.UPDATEUI_D,ID_temp+"::"+elapseTime+"ms"));//推送UI
                                                            lastElapseTimeInt = elapseTime_int;
                                                            if (deltaTime<=0)
                                                            {
                                                                break;
                                                            }
                                                        }
                                                        break;
                                                        case 2: {

                                                        }
                                                        break;
                                                    }
                                                }
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    } catch (SocketException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                            break;
                            case 2://Client port
                            {
                                String Head = "parse";
                                try {
                                    InetAddress ip_tem = InetAddress.getByName(Tcp_ip_context.getText().toString());
                                    int port_tem = Constant.SERVER_PORT;
                                    Log.d(Constant.TAG,"打印IP："+ip_tem+"打印Port："+port_tem);
                                } catch (UnknownHostException e) {
                                    e.printStackTrace();
                                }
                                if(lastIsThreadRun)
                                {
                                    break;
                                }
                                ThreadPoolUtils.execute(() -> {
                                    lastIsThreadRun = true;
                                    try {
                                        sendMeg2Server(Constant.I_AM_CLIENT, InetAddress.getByName(Tcp_ip_context.getText().toString()), Constant.SERVER_PORT);
                                    } catch (UnknownHostException e) {
                                        e.printStackTrace();
                                    }
                                    byte[] message = new byte[100];
                                    DatagramSocket datagramSocket = null;
                                    DatagramPacket datagramPacket = null;
                                    try {
                                        datagramSocket = new DatagramSocket(Constant.SERVER_PORT);
                                    } catch (SocketException e) {
                                        e.printStackTrace();
                                    }
                                    datagramPacket = new DatagramPacket(message, message.length);
                                    while (isThreadRun) {
                                        String time_tem = Long.toString(SystemClock.elapsedRealtime());// + "";
                                        String ID_temp = Device_id_Context.getText().toString();
                                        String str = Head + "," + 1 + "," + ID_temp + "," + time_tem;
                                        try {
                                            sendMeg2Server(str, InetAddress.getByName(Tcp_ip_context.getText().toString()), Constant.SERVER_PORT);
                                            assert datagramSocket != null;
                                            datagramSocket.receive(datagramPacket);
                                            String strMsg = new String(datagramPacket.getData()).trim();
                                            Log.d(Constant.TAG,"客户端收到："+strMsg);
                                            if (strMsg.equalsIgnoreCase("FireSecurity")) {//检测到Fire string 即可执行点火命令 点火之后会自动弹出fired消息 停止循环燃放
                                                EventBusUtil.getInstance().postEvent(new Event(Constant.Events.POSTFIRECMD, "Fire"));
                                                Log.d(Constant.TAG,"线程一直在执行，接收到了加密点火命令，点火命令内部弹出成功");
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                            }
                            break;
                        }
//                        switch (globle_role_var) {
//                            case 1:
//                                if(lastIsThreadRun)
//                                {
//                                    break;
//                                }
//                                ServerUtil.getInstance().startServer();
//                                ThreadPoolUtils.execute(() -> {
//                                    while (isThreadRun) {
//                                        try {
//                                            lastIsThreadRun = true;
//                                            String localID = Device_id_Context.getText().toString();
//                                            String localTime = SystemClock.elapsedRealtime()+"";
//                                            String server_re_meg = ServerUtil.getInstance().read;
//                                            if (server_re_meg!=null) {
//                                                if (server_re_meg.contains(",")) {
//                                                    //Log.d("LY","Fuck in");
//                                                    if (server_re_meg.contains(":Offline"))
//                                                        EventBusUtil.getInstance().postEvent(new Event(Constant.Events.UPDATEUI_D, localID + "Offline"));
//                                                    String re[] = server_re_meg.split(",");
//                                                    int isID = Integer.parseInt(re[1]);
//                                                    Boolean isIP = RegexUtils.isIP(re[0]);
//                                                    Boolean isTime = RegexUtils.isMatch(SystemClock.elapsedRealtime() + "", re[2]);
//                                                    //Log.d("LY", "isIP:" + isIP + " isID:" + isID + " isTime:" + isTime);
//                                                    if (isIP && isID < 100 && isID > 0) {
//                                                        ServerUtil.getInstance().sendServerMessage(localID + "," + localTime);
//                                                        String updateUI = isID + "::" + re[2] + "ms";
//                                                        EventBusUtil.getInstance().postEvent(new Event(Constant.Events.UPDATEUI_D, updateUI));
//                                                        Log.d("LY", "send meg alReady" + localID + "," + localTime);
//                                                        Thread.sleep(1000);
//                                                    }
//
//                                                }
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                });
//                                break;
//                            case 2:
//                                String IP = Tcp_ip_context.getText().toString();
//                                //Tcp_ip_context.setText(IP);
//                                Constant.SERVER_IP = IP;//Server 的 IP 是从系统获得
//                                if (lastIsThreadRun)
//                                {
//                                    break;
//                                }
//                                ClientUtil.getInstance().connectServer();//开启服务端
//                                ThreadPoolUtils.execute(()->{
//
//                                    while(isThreadRun) {
//
//                                        try {
//                                            String meg2Server_id = Device_id_Context.getText().toString();
//                                            String meg2Server_ip = Tcp_ip_context.getText() + "";
//                                            String meg2Server_time = SystemClock.elapsedRealtime() + "";
//                                            String meg2Server = meg2Server_ip + "," + meg2Server_id + "," + meg2Server_time;
//                                            String meg = ClientUtil.getInstance().message;
//                                            if (meg!=null) {
//                                                if (meg.contains(",")) {
//                                                    String[] tempRe = meg.split(",");
//                                                    if (Integer.parseInt(tempRe[0]) > 0) {
//                                                        boolean isInter = RegexUtils.isMatch(REGEX_NEGATIVE_INTEGER, tempRe[1]);
//                                                        if (isInter) {
//                                                            lastIsThreadRun = true;
//                                                            currentTime = Long.parseLong(tempRe[1]);
//                                                            long DeltaTime = currentTime - lastTime - 1000;
//                                                            isreceivedFServer = true;
//                                                            if (DeltaTime > 0) {
//                                                                ClientUtil.getInstance().sendClientMessage(meg2Server_ip + "," + meg2Server_id + "," + DeltaTime);
//                                                            }
//                                                        } else
//                                                            isreceivedFServer = false;
//                                                    }
//                                                }
//                                            }
//                                                Thread.sleep(1000);
//                                                lastTime = currentTime;
//                                                if (isreceivedFServer == false) {
//
//                                                    ClientUtil.getInstance().sendClientMessage(meg2Server);
//                                                }
//
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//
//                                    }
//                                });
//
//                                break;
//                        }
                    }
                    break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + globle_current_var);
                }
            }
            break;
            case R.id.tv_network:
                tv_network.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                Tcp_ip_context.setEnabled(true);
                globle_current_var = 4;
                SPUtils.getInstance().put(Constant.CURRENTITEM, globle_current_var);
                break;
            case R.id.tv_audio:
                tv_audio.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                Tcp_ip_context.setEnabled(false);
                globle_current_var = 2;
                SPUtils.getInstance().put(Constant.CURRENTITEM, globle_current_var);
                break;
            case R.id.tv_usb:
                tv_usb.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_btn.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                Tcp_ip_context.setEnabled(false);
                globle_current_var = 3;
                SPUtils.getInstance().put(Constant.CURRENTITEM, globle_current_var);
                break;
            case R.id.tv_btn://
                tv_btn.setBackgroundColor(getResources().getColor(R.color.yellow));
                tv_audio.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_network.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                tv_usb.setBackgroundColor(getResources().getColor(R.color.design_default_color_primary_dark));
                Tcp_ip_context.setEnabled(false);
                globle_current_var = 1;
                SPUtils.getInstance().put(Constant.CURRENTITEM, globle_current_var);
                break;
            default:
                break;
        }
    }

    //udp广播发送数据函数
    public static void  broadcast_send(String message, int target_port) throws UnknownHostException {
        String host_ip = Tcp_ip_context.getText().toString().trim();
        InetAddress bc_addr = InetAddress.getByName(host_ip);
        try {
            bc_addr = InetAddress.getByName("255.255.255.255");
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sendMeg2Server(message, bc_addr, target_port);
    }

    private void openDevice() {
        if (!mPhysicaloid.isOpened()) {
            if (mPhysicaloid.open()) { // default 9600bps

                //noinspection deprecation
                mPhysicaloid.addReadListener(new ReadLisener() {
                    String readStr;

                    // callback when reading one or more size buffer
                    @Override
                    public void onRead(int size) {
                        byte[] buf = new byte[size];

                        mPhysicaloid.read(buf, size);
                        try {
                            readStr = new String(buf, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            Log.e("lhl", e.toString());
                            return;
                        }
                    }
                });
            }
        }
    }

    private void onClickUpload(View v) {
        try {
            mPhysicaloid.upload(Boards.ARDUINO_UNO, getResources().getAssets().open("SerialEchoback.PocketDuino.hex"), mUploadCallback);
        } catch (RuntimeException e) {
            Log.e("lhl", e.toString());
        } catch (IOException e) {
            Log.e("lhl", e.toString());
        }
    }

    private void closeDevice() {
        if (mPhysicaloid.close()) {
            mPhysicaloid.clearReadListener();
        }
    }

    //****************************************************************
    // TODO : get intent when a USB device attached
    protected void onNewIntent(Intent intent) {
        String action = intent.getAction();
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            openDevice();
        }
    }
    //****************************************************************
}
